<?php

namespace CNEPAdmin\Controller;

use CNEPAdmin\Controller\CommonController;

class CategoryController extends CommonController {

    protected $_modelName = "Category";

    protected function setCode() {
        $this->_code = "Category";
    }

    public function index() {
        $this->checkPriv('category', 1, false);
		$this->assign('imgDomain',C('IMG_DOMAIN'));
        $this->_getOnePageData("getCategoryList", "getCategoryListLength");
    }

    /**
     * 得到条件查询数组
     * @return Array
     */
    protected function _getQueryArr(&$where, &$order) {

        if (strlen(trim(I("name"))) > 0) {
            $where['name'] = array("like", "%" . trim(I("name") . "%"));
        }

		$orderBy = 'sort';
        $asc = 'asc';
        if (intval(I("sDesc")) === 1) {
            $desc = 'desc';
        }
        if (strlen(trim(I("sOrderBy", ''))) > 0) {
            $orderBy = I("sOrderBy");
        }

        $order = array(
            $orderBy => $asc
        );

        return $where;
    }

    /**
     * 查看列表
     */
    

    public function saveCategory() {
        $id = I("categoryID");
        
        if ($id > 0) {
            $this->_updateCategory();
        } else {
            $this->_addCategory();
        }
    }

    /**
     *  添加
     */
    private function _addCategory() {
        $this->checkPriv('category', 2);
		!empty($_POST['img'])?$_POST['img']=$this->get_url_path(I('post.img')):"";
        $this->_setModel();
		
        $rt = $this->_model->addCategory();

        if ($rt) {
            $this->ajaxReturn(array('result' => 1));
        } else {
            $this->ajaxReturn(array('result' => 0, 'desc' => $this->_model->getLastSql. $this->_model->getError() . $this->_model->getDbError()));
        }
    }

    /**
     * 删除
     */
    public function deleteCategory() {
        $this->checkPriv('category', 2);

        $this->_setModel();
        $model = $this->_model;
        $rt = $model->deleteCategory(I("post.categoryID"));

        $rejson = $rt ? array('result' => 1) : array('result' => 0, 'desc' => $model->getError() . $model->getDbError());

        $this->ajaxReturn($rejson);
    }

    /**
     * 查看管理员信息
     */
    public function viewCategory() {
        $this->checkPriv('category', 1, false);

        $categoryid = intval(I("categoryID", 0));

        if ($categoryid > 0) { // 编辑
            $this->_setModel();
            $this->assign("arr", $this->_model->getCategoryById($categoryid));
        }

        $this->display();
    }

    /**
     * 更新信息
     */
    private function _updateCategory() {
        $this->checkPriv('category', 2);
		!empty($_POST['img'])?$_POST['img']=$this->get_url_path(I('post.img')):"";
        $this->_setModel();
		
        $admin = $this->_model;
        $rt = $admin->updateCategory();
        $rejson = $rt ? array('result' => 1) : array('result' => 0, 'desc' => $admin->getError() . $admin->getDbError());

        $this->ajaxReturn($rejson);
    }

}
